//index.js
const app = getApp()

Page({
  data: {
    openid: '',
    avatarUrl: './user-unlogin.png',
    nickname: '',
    userInfo: {},
    login: true,
    takeSession: false,
    requestResult: ''
  },

  onLoad: function() {
    if (!wx.cloud) {
      wx.redirectTo({
        url: '../chooseLib/chooseLib',
      })
      return
    }

    // 获取用户信息
    this.checkSettingForUserInfo()
  },

  // 检测是否获得权限并获取用户信息
 checkSettingForUserInfo: async function() {
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          wx.getUserInfo({
            success: res => {
              this.setData({
                login: true,
                avatarUrl: res.userInfo.avatarUrl,
                nickname: res.userInfo.nickName,
                userInfo: res.userInfo
              })
              app.globalData.userInfo = res.userInfo;

              // 获取用户的openid
              this.onGetOpenid()
            }
          })
        } else {
          this.setData({
            login: false,
          })
        }
      }
    })
  },

  // 获取用户信息
  onGetUserInfo: async function(e) {
    if (!this.data.login && e.detail.userInfo) {
      this.setData({
        login: true,
        avatarUrl: e.detail.userInfo.avatarUrl,
        nickname: e.detail.userInfo.nickName,
        userInfo: e.detail.userInfo
      })
      app.globalData.userInfo = e.detail.userInfo;

      // 获取用户的openid
      this.onGetOpenid()
    }
  },

  // 获取用户的openid
  onGetOpenid: async function() {
    // 调用云函数
    wx.cloud.callFunction({
      name: 'login',
      data: {},
      success: res => {
        console.log('[云函数] [login] user openid: ', res.result.openid)
        app.globalData.openid = res.result.openid;
        this.setData({
          openid: res.result.openid
        })
        this.insertUser()
      },
      fail: err => {
        console.error('[云函数] [login] 调用失败', err)
      }
    })
  },

  // 插入用户数据到 [db](user)
  insertUser: async function() {
    const db = wx.cloud.database()
    const userArr = await db.collection("user").where({
      _openid: this.data.openid
    }).get()
    console.log('[云数据库] [user] query: ', userArr.data.length)
    if (userArr.data.length > 0) {
      this.redirectToPage(userArr.data[0])
      return
    }
    db.collection("user").add({
      data: {
        nickname: this.data.nickname,
        avatar: this.data.avatarUrl,
        status: "normal",
        room: "0",
        solve: false,
        status: "normal",
        role: "",
      },
      success: function(res) {
        console.log('[云数据库] [user] insert: ', res)
      },
      fail: function(res) {
        console.log('[云数据库] [user] insert 调用失败: ', res)
      }
    })
  },

  // 根据用户当前所处的状态，加载指定的页面
  redirectToPage: function(user) {
    if (user.status == "ready") {
      wx.reLaunch({
        url: '../startGame/startGame?room=' + user.room
      })
    } else if (user.status == "gaming") {
      wx.reLaunch({
        url: '../playGame/playGame?room=' + user.room
      })
    }
  }
})
